package com.maincode;

import android.app.Application;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.lidroid.xutils.http.client.HttpRequest;
import com.util.HttpUrl;
import com.util.xutil.HttpParams;
import com.util.xutil.HttpRequestCallBack;
import com.util.xutil.HttpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by djx on 16/1/19.
 * email dengjianxin09@163.com
 */
public class WccApplication extends Application {
    // 百度地图
    public LocationClient mLocationClient = null;
    public static BDLocation location;
    public ArrayList<PoiInfo> poiList = new ArrayList<PoiInfo>();
    public BDLocationListener myListener = new MyLocationListener();

    //相册路径
    public static final String photoPath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera";
    public static File cacheFile;

    @Override
    public void onCreate() {
        mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
        mLocationClient.registerLocationListener(myListener); // 注册监听函数
        initLocation();
        super.onCreate();
        cacheFile = new File(this.getExternalCacheDir().getPath());
    }

    // 初始化地图
    private void initLocation() {
        SDKInitializer.initialize(this);
        location = new BDLocation();
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(getApplicationContext(), 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
        option.setAddrType("all");
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(true);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);
    }

    GeoCoder mSearch;

    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                // 没有检索到结果
            }
            // 获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                // 没有找到检索结果
            }
            // 获取反向地理编码结果
            if (result.getPoiList() != null)
                poiList.addAll((ArrayList<PoiInfo>) result.getPoiList());
        }
    };

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == 161) {
                if (WccApplication.this.location != null && location != null) {
                    if (WccApplication.this.location.getLongitude() != location.getLongitude() || WccApplication.this.location.getLatitude() != location.getLatitude()) {
                        WccApplication.this.location = location;
//                        if (getUid() != null && !getUid().equals("")) {
                        //定位成功发起检索
                        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(location.getLatitude(), location.getLongitude())));
//                            new UpdateLngLat(getApplicationContext());
//                        }
                        reportPosition();
                    }
                } else {
                    WccApplication.this.location = location;
                }
            } else {
                mLocationClient.requestLocation();
                return;
            }

        }
    }

    /**
     * 发送定位信息
     */
    private void reportPosition() {
        HttpParams httpParams = new HttpParams(HttpUrl.getUrl(HttpUrl.REPORTPOSITION));
        httpParams.putString("lat", location.getLatitude() + "");
        httpParams.putString("lng", location.getLongitude() + "");
        WCCBaseActivity activity = new WCCBaseActivity();
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.send(HttpRequest.HttpMethod.POST, httpParams.toString(), new HttpRequestCallBack<String>(String.class, activity, false) {
            @Override
            protected void onSuccess(String s) {
                Log.e("Location", s);
            }
        });
    }
}
